/*
 * Copyright (c) 2024 Cshoo Org. All Rights Reserved.
 *
 * author:杨翼
 * date: 2025年6月14日
 * description:guest stage组件html渲染后端java model
 */

package org.cshoo.presentation.yato.model;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.models.annotations.DefaultInjectionStrategy;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.injectorspecific.Self;
import org.apache.sling.models.annotations.injectorspecific.ValueMapValue;

import java.util.Iterator;
import java.util.Objects;

@Model(adaptables = Resource.class, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
@Slf4j
@Setter
public class GuestStage {

    @Self
    private Resource resource;

    @ValueMapValue
    private String title;

    @ValueMapValue
    private String description;

    /**
     * words list组件传出json类型的数据，供前端react全局使用,
     * 形成SPA方式，即aem只作为初始渲染，后续完全交由react控制
     *
     * @return 组件配置的数据
     */
    public String getJsonData() {
        JsonObject jsonObject = new JsonObject();

        jsonObject.addProperty("title", title);
        jsonObject.addProperty("description", description);

        JsonArray jsonArray = new JsonArray();
        log.info("resource:{}", resource);
        Resource femaleGuestsResource = resource.getChild("femaleGuests");
        if (Objects.nonNull(femaleGuestsResource)) {
            Iterator<Resource> femaleGuestsIterator = femaleGuestsResource.listChildren();
            Gson gson = new Gson();
            while (femaleGuestsIterator.hasNext()) {
                Resource femaleGuestResource = femaleGuestsIterator.next();
                log.info("femaleGuestResource:{}", femaleGuestResource);
                ValueMap valueMap = femaleGuestResource.getValueMap();
                FemaleGuest femaleGuest = new FemaleGuest();
                femaleGuest.setName(valueMap.get("name", String.class));
                femaleGuest.setHeight(valueMap.get("height", Float.class));
                femaleGuest.setWeight(valueMap.get("weight", Float.class));
                femaleGuest.setEducational(valueMap.get("educational", String.class));
                femaleGuest.setIncome(valueMap.get("income", Float.class));
                log.info("femaleGuest:{}", femaleGuest);
                jsonArray.add(gson.toJsonTree(femaleGuest, FemaleGuest.class));
            }
        }
        jsonObject.add("femaleGuests", jsonArray);

        String result = jsonObject.toString();
        log.info("result:{}", result);

        return result;
    }
}
